import {createRouter, createWebHashHistory} from "vue-router"
import {routerConfig} from "@/config/router.config";
import {getStore, setStore} from "@/api/utils";
import {routerStore} from "@/store/store";
import {dealWithRoute} from "./dealWithRoute";

const router = createRouter({
    history: createWebHashHistory(),
    routes: routerConfig,
})

// 路由白名单
let whiteList = ['/login', '/QQRedirect', '/404']
// 为routerStore赋初值
let store = null

router.beforeEach(async (to, from, next) => {
    store = routerStore()
    let user_token = getStore('token') ?? '';
    let isLoadRouters = store.asyncRoutesMark
    let routes = getStore('routes')
    // 未登录
    if (user_token === '') {
        if (to.path === '/login') {
            next()
        } else {
            if (whiteList.indexOf(to.path) != -1) {
                next()
            } else {
                next('/login')
            }
        }
    } else {
        if (to.path === '/login') {
            next('/dashboard')
        } else {
            // 用户已登录
            if (user_token && JSON.stringify(routes) != '[]') {
                if (isLoadRouters) {
                    next()
                } else {
                    // 解决刷新页面空白
                    let route = getStore('routes')
                    store.setRouters(route)
                    store.setAsyncRoutesMark(true)

                    // 动态添加路由
                    let routerData = getStore('routes')
                    dealWithRoute(routerData)
                    next({...to, replace: true})
                }
            } else {
                store.setAsyncRoutesMark(false)
                store.setRouters([])
                setStore('token', '')
                setStore('routes', [])
                next('/login')
            }
        }
    }
})

router.afterEach((to) => {
    document.title = to.meta.title
})


export default router

